#!/usr/bin/python3
# coding=utf-8
import sys
import json


def drop_result(raw):
    '''
    fd = open("./test.json", 'r')
    raw = fd.read().strip()
    fd.close()
    '''
    postprocess_result = {
        "code": 0,
        "err_msg": "",
        "result": {}
    }
    if raw.find("tcp_state") == -1 and len(raw) != 0:
        postprocess_result["code"] = 1
        postprocess_result["err_msg"] = f"Diagnosis failed:\n{raw}"
        print(json.dumps(postprocess_result, indent=4))
        return

    raw = raw.strip()

    newdrop = {}
    newdrop["RetranStat"] = {}
    newdrop["RetranStat"]["data"] = []

    retran_cnt = 0
    if len(raw) != 0:
        for s in raw.split('\n'):
            retran_cnt += 1
            item = json.loads(s)
            newdrop["RetranStat"]["data"].append({
                "id": str(retran_cnt), "ip": item["ap"], "tcpState": item["tcp_state"],
                "caState": item["ca_state"], "retranCnt": item["times"]
            })

    newdrop["summary"] = "diagnones result: total capture {} retransmits".format(
        retran_cnt)
    postprocess_result["result"] = newdrop
    print(json.dumps(postprocess_result, ensure_ascii=False))


def extract_params():
    path, res, task_id = sys.argv[1], "", sys.argv[2]
    with open(path, 'r') as tmp:
        res = tmp.read()
    return res, task_id


if __name__ == "__main__":
    res, _ = extract_params()
    drop_result(res)
